package com.cardpay.user.listener;

import com.cardpay.common.log.Log;
import com.cardpay.common.util.ConstantUtil;
import com.cardpay.user.OnlineUser;
import com.cardpay.user.OnlineUserService;
import com.cardpay.user.User;
import org.slf4j.Logger;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 负责监听每次用户请求，每次用户请求到达时，如果是新的会话，将相关信息存入数据库；<br>
 * 如果是老的会话，则更新数据库中已有的在线记录。
 * 
 * @author ChenFangjie(2015/9/2 20:52:42)
 * 
 * @since 1.1.0
 * 
 * @version 1.1.0
 *
 */
public class RequestListener implements ServletRequestListener {

    private static final Logger log = Log.get();

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        //获取sessionId
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();

        HttpSession session = request.getSession();
        String sessionId = session.getId();

        // 获取访问的IP和正在访问的页面
        String ip = request.getRemoteAddr();
        String url = null;
        if (null != request.getQueryString()) {
            url = String.format("%s?%s", request.getRequestURI(), request.getQueryString());
        }
        else {
            url = request.getRequestURI();
        }

        User currentUser = (User) session.getAttribute(ConstantUtil.CURRENT_USER);
        String userId ;
        String userName ;

        // 未登录用户显示为游客
        if(null == currentUser) {
            userId = "游客";
            userName = "游客";
        }else{
            userId = currentUser.getId();
            userName = currentUser.getUserName();
        }

        OnlineUserService service = new OnlineUserService();

        OnlineUser onlineUser = service.find(sessionId);

        //sessionid已存在则修改在线信息
        if (null != onlineUser) {
            onlineUser.setUserId(userId);
            onlineUser.setLoginName(userName);
            onlineUser.setUserName(userName);
            onlineUser.setPageUrl(url);
            onlineUser.setLastAccessTime(System.currentTimeMillis());

            service.update(onlineUser);
        }
        //不存在则新增数据
        else {
            long currentTimeMillis = System.currentTimeMillis();

            onlineUser = new OnlineUser();
            onlineUser.setSessionId(sessionId);
            onlineUser.setUserId(userId);
            onlineUser.setLoginName(userName);
            onlineUser.setUserName(userName);
            onlineUser.setClientIp(ip);
            onlineUser.setPageUrl(url);
            onlineUser.setCreateTime(currentTimeMillis);
            onlineUser.setLastAccessTime(currentTimeMillis);

            service.add(onlineUser);
        }

    }

}
